import axios from 'axios'
import {ElLoading, ElMessage, ElMessageBox, ElNotification} from 'element-plus'
import {getAccessToken} from "@/common/utils/cache";

let downloadLoadingInstance;

//是否显示重新登录
export let isReLogin = {show: false};

axios.defaults.headers['Content-Type'] = 'application/json;charset=utf-8'

// 创建axios实例
const service = axios.create({
    baseURL: import.meta.env.VITE_API_URL,
    timeout: 60 * 1000
})

// request拦截器
service.interceptors.request.use(config => {
    config.headers["Token"] = getAccessToken();
    return config
}, error => {
    //console.log(error)
    Promise.reject(error)
})

// 响应拦截器
service.interceptors.response.use(res => {
    //console.log(res)
    const code = res.data.code || 200;
    const message = res.data.message

    // 二进制数据则直接返回
    if (res.request.responseType === 'blob' || res.request.responseType === 'arraybuffer') {
        return res.data
    }

    //错误
    if (code === 401) {
        ElMessage({message: message, type: 'error'})
        return Promise.reject(new Error(message))
    }

    //Token失效
    if (code === 410) {
        //console.log(" location.href ", location.href)
        //console.log(" location.href ",)
        if (!isReLogin.show && !location.href.includes("/login")) {
            isReLogin.show = true;
            ElMessageBox.confirm('登录状态已过期，您可以继续留在该页面，或者重新登录', '系统提示', {
                confirmButtonText: '重新登录', cancelButtonText: '取消', type: 'warning'
            }).then(() => {
                isReLogin.show = false;
                location.href = '/index';
            }).catch(() => {
                isReLogin.show = false;
            });
        }
        return Promise.reject('无效的会话，或者会话已过期，请重新登录。')
    }

    //错误
    if (code === 500) {
        ElMessage({message: message, type: 'error'})
        return Promise.reject(new Error(message))
    }

    //重复提交
    if (code === 600) {
        ElMessage({message: message, type: 'warning'})
        return Promise.reject(new Error(message))
    }

    //无法识别
    if (code !== 200) {
        ElMessage({message: message, type: 'warning'})
        return Promise.reject('error')
    }

    return Promise.resolve(res.data)
}, (error) => {
    //console.log('err: ' + error)

    let {message} = error;
    if (message === "Network Error") {
        message = "服务正在更新，暂时无法访问。";
    } else if (message.includes("timeout")) {
        message = "系统接口请求超时";
    } else if (message.includes("Request failed with status code")) {
        message = error.response.data.message ? error.response.data.message : "访问服务接口失败，返回状态码：" + message.substring(message.length - 3);
    }
    ElNotification.warning({title: message})

    return Promise.reject(error)

})

// 通用下载方法
export function download(url, params, filename, config) {
    downloadLoadingInstance = ElLoading.service({text: "正在下载数据，请稍候", background: "rgba(0, 0, 0, 0.7)",})
    return service.post(url, params, {
        transformRequest: [(params) => {
            return tansParams(params)
        }], headers: {'Content-Type': 'application/x-www-form-urlencoded'}, responseType: 'blob', ...config
    }).then(async (data) => {
        const isBlob = (data.type !== 'application/json');
        if (isBlob) {
            const blob = new Blob([data])
            saveAs(blob, filename)
        } else {
            const resText = await data.text();
            ElMessage.error(JSON.parse(resText).message);
        }
        downloadLoadingInstance.close();
    }).catch((r) => {
        console.error(r)
        ElMessage.error('下载文件出现错误，请联系管理员！')
        downloadLoadingInstance.close();
    })
}


/**
 * 参数处理
 * @param {"id":10} params  参数
 */
export function tansParams(params) {
    let result = ''
    for (const propName of Object.keys(params)) {
        const value = params[propName];
        let part = encodeURIComponent(propName) + "=";
        if (value !== null && value !== "" && typeof (value) !== "undefined") {
            if (typeof value === 'object') {
                for (const key of Object.keys(value)) {
                    if (value[key] !== null && value[key] !== "" && typeof (value[key]) !== 'undefined') {
                        let params = propName + '[' + key + ']';
                        let subPart = encodeURIComponent(params) + "=";
                        result += subPart + encodeURIComponent(value[key]) + "&";
                    }
                }
            } else {
                result += part + encodeURIComponent(value) + "&";
            }
        }
    }
    return result
}

export function postForm(url, data, headers) {

    let config = {url, data, method: "post"}

    config.headers = {"Content-Type": "application/x-www-form-urlencoded",}

    if (headers) config.headers = headers;

    return service(config)

}

export function postJSON(url, data, headers) {

    let config = {url, data, method: "post"}

    config.headers = {}

    if (headers) config.headers = headers;

    return service(config)

}

export default service
